package com.stylefeng.guns.modular.rmbCashReceipts.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.borrowing.service.IBorrowingInfoService;
import com.stylefeng.guns.modular.borrowing.service.ICustomerinfoService;
import com.stylefeng.guns.modular.cash.service.IDetailsService;
import com.stylefeng.guns.modular.expenditure.service.IExpenditureService;
import com.stylefeng.guns.modular.rmbCashReceipts.service.IRmbCashReceiptsService;
import com.stylefeng.guns.modular.system.model.Customerinfo;
import com.stylefeng.guns.modular.system.model.Details;
import com.stylefeng.guns.modular.system.model.RmbCashReceipts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RMB银行其它收入/其它支出明细控制器
 *
 * @author fengshuonan
 * @Date 2018-07-27 16:36:31
 */
@Controller
@RequestMapping("/rmbCashReceipts")
public class RmbCashReceiptsController extends BaseController {

    private String PREFIX = "/rmbCashReceipts/rmbCashReceipts/";

    @Autowired
    private IRmbCashReceiptsService rmbCashReceiptsService;

    @Autowired
    private IDetailsService detailsService;
    @Autowired
    private IBorrowingInfoService borrowingInfoService;
    @Autowired
    private ICustomerinfoService customerinfoService;
    @Autowired
    private IExpenditureService expenditureService;


    /**
     * 跳转到RMB银行其它收入/其它支出明细首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "rmbCashReceipts.html";
    }

    /**
     * 跳转到添加RMB银行其它收入/其它支出明细
     */
    @RequestMapping("/rmbCashReceipts_add")
    public String rmbCashReceiptsAdd(Model model) {
        List<Details> list=detailsService.selectList(null);
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        model.addAttribute("Details",list);
        Customerinfo customerinfo = new Customerinfo();
        customerinfo.setCustomercode("");
        customerinfo.setCustomername("请选择");
        customerList.add(0,customerinfo);
        model.addAttribute("Customerinfos",customerList);
        return PREFIX + "rmbCashReceipts_add.html";
    }

    /**
     * 跳转到导出页面
     */
    @RequestMapping("/rmbCashReceipts_export")
    public String rmbCashReceiptsExport() {
        return PREFIX + "rmbCashReceipts_export.html";
    }

    /**
     * 跳转到修改RMB银行其它收入/其它支出明细
     */
    @RequestMapping("/rmbCashReceipts_update/{rmbCashReceiptsId}")
    public String rmbCashReceiptsUpdate(@PathVariable Integer rmbCashReceiptsId, Model model) {
        List<Details> list=detailsService.selectList(null);
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        Customerinfo customerinfo = new Customerinfo();
        customerinfo.setCustomercode("");
        customerinfo.setCustomername("请选择");
        customerList.add(0,customerinfo);
        model.addAttribute("Details",list);
        model.addAttribute("Customerinfos",customerList);
        RmbCashReceipts rmbCashReceipts = rmbCashReceiptsService.selectById(rmbCashReceiptsId);
        model.addAttribute("item",rmbCashReceipts);
        LogObjectHolder.me().set(rmbCashReceipts);
        return PREFIX + "rmbCashReceipts_edit.html";
    }

    /**
     * 获取RMB银行其它收入/其它支出明细列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(RmbCashReceipts rmbCashReceipts,@RequestParam(required=false) String beginDate,@RequestParam(required=false) String endDate) throws Exception {



        Page<RmbCashReceipts> page = new PageFactory<RmbCashReceipts>().defaultPage();
        //组装查询
        EntityWrapper<RmbCashReceipts> wrapper = new EntityWrapper<RmbCashReceipts>();
        wrapper.eq("platform",rmbCashReceipts.getPlatform());
        if (rmbCashReceipts.getType()!=null)
            wrapper.eq("type",rmbCashReceipts.getType());

        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revdate", beginDate);
        }else{
            wrapper.ge("revdate", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revdate", endDate);
        }else{
            wrapper.le("revdate", DateUtil.today(1));
        }
        wrapper.orderBy("revdate",false);

        Page<RmbCashReceipts> rmbCashReceiptsPage = rmbCashReceiptsService.selectPage(page,wrapper);
        rmbCashReceiptsPage.setRecords((List<RmbCashReceipts>)new BaseModelWarpper(rmbCashReceiptsPage.getRecords(),RmbCashReceipts.class).warpToObj());
        return super.packForBT(rmbCashReceiptsPage);
    }

    @RequestMapping(value = "/total")
    @ResponseBody
    public Object total(RmbCashReceipts rmbCashReceipts,@RequestParam(required=false) String beginDate,@RequestParam(required=false) String endDate) throws Exception {


        //组装查询
        EntityWrapper<RmbCashReceipts> wrapper = new EntityWrapper<RmbCashReceipts>();
        wrapper.eq("platform",rmbCashReceipts.getPlatform());
        if (rmbCashReceipts.getType()!=null)
            wrapper.eq("type",rmbCashReceipts.getType());
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revdate", beginDate);
        }else{
            wrapper.ge("revdate", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revdate", endDate);
        }else{
            wrapper.le("revdate", DateUtil.today(1));
        }

        List<RmbCashReceipts> rmbCashReceiptsList = rmbCashReceiptsService.selectList(wrapper);
        double income = 0;
        double payout =0;
        for (RmbCashReceipts rmbCashReceipts1:rmbCashReceiptsList){
            if (rmbCashReceipts1.getType()==RmbCashReceipts.Enum_Type.收款.value)
                income += rmbCashReceipts1.getAmount();
            else
                payout += rmbCashReceipts1.getAmount();
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("income",income);
        resultMap.put("payout",payout);
        return resultMap;

    }

    /**
     * 新增RMB银行其它收入/其它支出明细
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(RmbCashReceipts rmbCashReceipts) {
        String platform = ShiroKit.getUser().getDeptcode();
        rmbCashReceipts.setUpdatetime(new Date());
        rmbCashReceipts.setCreattime(new Date());
        if (rmbCashReceipts.getRevdate()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表统计时间不能为空");
        }
        rmbCashReceipts.setPlatform(platform);
        Long order_number = System.currentTimeMillis();
        rmbCashReceipts.setOrderNumber(order_number.toString());

        rmbCashReceiptsService.insert(rmbCashReceipts);
        //将对应的数据插入银行日结
        expenditureService.addAmount(rmbCashReceipts);

        //添加到应收应付中
        if (rmbCashReceipts.getSummary()==RmbCashReceipts.Enum_Summary.应付.value.intValue()
                ||rmbCashReceipts.getSummary()==RmbCashReceipts.Enum_Summary.应收.value.intValue())
                borrowingInfoService.insertBorrowing(platform,rmbCashReceipts);

        return SUCCESS_TIP;
    }

    /**
     * 删除RMB银行其它收入/其它支出明细
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer rmbCashReceiptsId) {
        RmbCashReceipts rmbCashReceipts = rmbCashReceiptsService.selectById(rmbCashReceiptsId);
        if (!rmbCashReceipts.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"对不起！此数据不能删除，请检查您的权限");
        boolean isture = rmbCashReceiptsService.deleteById(rmbCashReceiptsId);
        if (isture){
            if (rmbCashReceipts.getSummary()==RmbCashReceipts.Enum_Summary.应付.value.intValue()||rmbCashReceipts.getSummary()==RmbCashReceipts.Enum_Summary.应收.value.intValue()) {
                borrowingInfoService.delete(ShiroKit.getUser().getDeptcode(), rmbCashReceipts.getOrderNumber());
            }

        //减少银行收支对应的其他收支和手续费
        expenditureService.deleteAmount(rmbCashReceipts);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改RMB银行其它收入/其它支出明细
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(RmbCashReceipts rmbCashReceipts) {

        RmbCashReceipts oldRmbCashReceipts = rmbCashReceiptsService.selectById(rmbCashReceipts.getId());
        if (!oldRmbCashReceipts.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"对不起您无权修改");
        rmbCashReceipts.setPlatform(ShiroKit.getUser().getDeptcode());
        rmbCashReceipts.setUpdatetime(new Date());
        rmbCashReceiptsService.updateById(rmbCashReceipts);
        //如果为借贷则修改应收应付表
        if (detailsService.selectById(rmbCashReceipts.getSummary()).getType()== RmbCashReceipts.Enum_DetailType.借贷.value) {
            borrowingInfoService.update(rmbCashReceipts, oldRmbCashReceipts);
        }
        expenditureService.updateAmount(oldRmbCashReceipts,rmbCashReceipts);

        return SUCCESS_TIP;
    }

    /**
     * RMB银行其它收入/其它支出明细详情
     */
    @RequestMapping(value = "/detail/{rmbCashReceiptsId}")
    @ResponseBody
    public Object detail(@PathVariable("rmbCashReceiptsId") Integer rmbCashReceiptsId) {
        return rmbCashReceiptsService.selectById(rmbCashReceiptsId);
    }


    /**
     * 描述:下载rmb应收收支明细
     * 创建人: laoyu
     * 日期: 2018/8/6 0006
     * 时间: 上午 9:29
     */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response, String beginDate,String endDate,int type) throws Exception {



        //查询要导出工资
        if (StringUtils.isBlank(beginDate)||StringUtils.isNotBlank(endDate)){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请选择要导出的资金预算表时间");
        }

        String platform = ShiroKit.getUser().getDeptcode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        EntityWrapper<RmbCashReceipts> wrapper  = new EntityWrapper<>();
        wrapper.eq("platform",platform);
        wrapper.eq("type",type);
        wrapper.ge("revdate",simpleDateFormat.parse(beginDate));
        wrapper.le("revdate",simpleDateFormat.parse(endDate));

        List<RmbCashReceipts> rmbCashReceiptsList = rmbCashReceiptsService.selectList(wrapper);

        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/rmbCash.xlsx");

        modelMap.put(TemplateExcelConstants.FILE_NAME, platform.toUpperCase()+beginDate.substring(0,7).replace("-","年")+"月RMB银行其它收入/其它支出明细分类表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, rmbCashReceiptsService.load(rmbCashReceiptsList,beginDate,endDate,platform));
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }
}
